//
//  CircleToolBarView.m
//  Malena
//
//  Created by Wang Shuguang on 12-11-8.
//  Copyright (c) 2012年 Dawn. All rights reserved.
//


#import "CircleToolBarView.h"
#import <QuartzCore/QuartzCore.h>

#define TOOLBUTTONTAG 1000
#define RADIUS_FAR 120.0
#define RADIUS 110.0
#define RADIUS_NEAR 100.0
#define THETA 0//(asin(16.0/RADIUS))
#define ICONWIDTH 45
@implementation CircleToolBarView
@synthesize delegate;
@dynamic isPlaying;
@synthesize position;

- (void)dealloc{
    [coordinates release];
    [coordinatesFar release];
    [coordinatesNear release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame iconArray:(NSArray *)toolIconArray position:(CircleToolBarPosition)pos
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        self.position = pos;
        count = toolIconArray.count;
        theta = (M_PI_2 - THETA * 2)/(count - 1);
        showed = NO;
        self.clipsToBounds = NO;
        coordinates = [[NSMutableArray alloc] initWithCapacity:count];
        coordinatesFar = [[NSMutableArray alloc] initWithCapacity:count];
        coordinatesNear = [[NSMutableArray alloc] initWithCapacity:count];
        [self refreshCoordinates];
        
        CGRect rect = CGRectNull;
        switch (position) {
            case CircleToolBarLeftTop:{
                rect = CGRectMake(0, 0, ICONWIDTH, ICONWIDTH);
                break;
            }
            case CircleToolBarLeftBottom:{
                rect = CGRectMake(0, frame.size.height - ICONWIDTH, ICONWIDTH, ICONWIDTH);
                break;
            }
            case CircleToolBarRightTop:{
                rect = CGRectMake(frame.size.width - ICONWIDTH, 0, ICONWIDTH, ICONWIDTH);
                break;
            }
            case CircleToolBarRightBottom:{
                rect = CGRectMake(frame.size.width - ICONWIDTH, frame.size.height - ICONWIDTH, ICONWIDTH, ICONWIDTH);
                break;
            }
            default:
                break;
        }
        
        
        
        // 功能按钮
        for (int i= 0;i < count;i++) {
            UIButton *toolBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [toolBtn setBackgroundImage:[UIImage imageNamed:[toolIconArray objectAtIndex:i]] forState:UIControlStateNormal];
            toolBtn.tag = TOOLBUTTONTAG + i;
            toolBtn.frame = rect;
            [toolBtn addTarget:self action:@selector(toolBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:toolBtn];
            
            toolBtn.alpha = 0.6;

            
        }
        
        
        

        // 触发按钮
        baseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [baseButton setBackgroundImage:[UIImage imageNamed:@"bar.png"] forState:UIControlStateNormal];
        [baseButton addTarget:self action:@selector(showTools:) forControlEvents:UIControlEventTouchUpInside];
        baseButton.frame = rect;
        baseButton.tag = TOOLBUTTONTAG - 1;
        [self addSubview:baseButton];
        
        basePoint = baseButton.center;
    }
    return self;
}
- (void) refreshCoordinates{
    [coordinatesNear removeAllObjects];
    [coordinatesFar removeAllObjects];
    [coordinates removeAllObjects];
    float x,y;
    for (int i = 0; i < count; i++) {
        double cosf_theat = cosf(i * theta + THETA);
        double sinf_theat = sinf(i * theta + THETA);
        x = cosf_theat * RADIUS;
        y = sinf_theat * RADIUS;
        [coordinates addObject:[NSValue valueWithCGSize:CGSizeMake(x, y)]];
        
        x = cosf_theat * RADIUS_FAR;
        y = sinf_theat * RADIUS_FAR;
        [coordinatesFar addObject:[NSValue valueWithCGSize:CGSizeMake(x , y)]];
        
        x = cosf_theat * RADIUS_NEAR;
        y = sinf_theat * RADIUS_NEAR;
        [coordinatesNear addObject:[NSValue valueWithCGSize:CGSizeMake(x , y)]];
    }
}

- (CGPoint) getPoint:(CGPoint)point{
    switch (position) {
        case CircleToolBarLeftTop:{
            break;
        }
        case CircleToolBarLeftBottom:{
            point.x = basePoint.x + point.x;
            point.y = basePoint.y - point.y;
            break;
        }
        case CircleToolBarRightTop:{
            point.x = basePoint.x - point.x;
            point.y = basePoint.y + point.y;
            break;
        }
        case CircleToolBarRightBottom:{
            point.x = basePoint.x - point.x;
            point.y = basePoint.y - point.y;
            break;
        }
        default:
            break;
    }
    return point;
}

- (CGPoint) getPointAtIndex:(NSInteger)index{
    CGPoint point = [[coordinates objectAtIndex:index] CGPointValue];
    return [self getPoint:point];
}

- (CGPoint) getFarPointAtIndex:(NSInteger)index{
    CGPoint point = [[coordinatesFar objectAtIndex:index] CGPointValue];
    return [self getPoint:point];
}

- (CGPoint) getNearPointAtIndex:(NSInteger)index{
    CGPoint point = [[coordinatesNear objectAtIndex:index] CGPointValue];
    return [self getPoint:point];
}

- (void) closeItems{
    if (!showed) {
        return;
    }
    showed = NO;
    [UIView animateWithDuration:0.2f animations:^{
        baseButton.transform = CGAffineTransformMakeRotation(0);
    }];
    for (int i = 0; i < count; i++) {
        CGPoint endPoint = [self getPointAtIndex:i];
        CGPoint farPoint = [self getFarPointAtIndex:i];
        // CGPoint nearPoint = [self getNearPointAtIndex:i];
        UIButton *button = (UIButton *)[self viewWithTag:TOOLBUTTONTAG + i];
        
        CAKeyframeAnimation *rotateAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotateAnimation.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f],[NSNumber numberWithFloat:M_PI * 2],[NSNumber numberWithFloat:0.0f], nil];
        rotateAnimation.duration = 0.5f;
        rotateAnimation.keyTimes = [NSArray arrayWithObjects:
                                    [NSNumber numberWithFloat:.0],
                                    [NSNumber numberWithFloat:.4],
                                    [NSNumber numberWithFloat:.5], nil];
        
        CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        positionAnimation.duration = 0.5f;
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, endPoint.x, endPoint.y);
        CGPathAddLineToPoint(path, NULL, farPoint.x, farPoint.y);
        CGPathAddLineToPoint(path, NULL, basePoint.x, basePoint.y);
        positionAnimation.path = path;
        CGPathRelease(path);
        
        CAAnimationGroup *animationgroup = [CAAnimationGroup animation];
        animationgroup.animations = [NSArray arrayWithObjects:positionAnimation, rotateAnimation, nil];
        animationgroup.duration = 0.5f;
        animationgroup.fillMode = kCAFillModeForwards;
        animationgroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [button.layer addAnimation:animationgroup forKey:@"Close"];
        button.center = basePoint;
    }

}

- (void) expandItems{
    if (showed) {
        return;
    }
    showed = YES;
    
    
    [UIView animateWithDuration:0.2f animations:^{
        baseButton.transform = CGAffineTransformMakeRotation(M_PI_4);
    }];
    
    for (int i = 0; i < count; i++) {
        CGPoint endPoint = [self getPointAtIndex:i];
        CGPoint farPoint = [self getFarPointAtIndex:i];
        CGPoint nearPoint = [self getNearPointAtIndex:i];
        UIButton *button = (UIButton *)[self viewWithTag:TOOLBUTTONTAG + i];
        
        CAKeyframeAnimation *rotateAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotateAnimation.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:M_PI],[NSNumber numberWithFloat:0.0f], nil];
        rotateAnimation.duration = 0.5f;
        rotateAnimation.keyTimes = [NSArray arrayWithObjects:
                                    [NSNumber numberWithFloat:.3],
                                    [NSNumber numberWithFloat:.4], nil];
        
        CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        positionAnimation.duration = 0.5f;
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, basePoint.x, basePoint.y);
        CGPathAddLineToPoint(path, NULL, farPoint.x, farPoint.y);
        CGPathAddLineToPoint(path, NULL, nearPoint.x, nearPoint.y);
        CGPathAddLineToPoint(path, NULL, endPoint.x, endPoint.y);
        positionAnimation.path = path;
        CGPathRelease(path);
        
        CAAnimationGroup *animationgroup = [CAAnimationGroup animation];
        animationgroup.animations = [NSArray arrayWithObjects:positionAnimation, rotateAnimation, nil];
        animationgroup.duration = 0.5f;
        animationgroup.fillMode = kCAFillModeForwards;
        animationgroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [button.layer addAnimation:animationgroup forKey:@"Expand"];
        button.center = endPoint;
    }
}
         
- (void) showTools:(id)sender{
    
    if (showed) {
        [self closeItems];
    }else{
        [self expandItems];
    }
}



//-(void)imgSingleTap:(UIGestureRecognizer *)gestureRecognizer{
//	if ([delegate respondsToSelector:@selector(didClickOutside)]) {
//		[delegate didClickOutside];
//	}
//}

#pragma mark -
#pragma mark HitTest
-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    
    if (point.x > baseButton.frame.origin.x
        && point.x < baseButton.frame.origin.x + baseButton.frame.size.width
        && point.y > baseButton.frame.origin.y
        && point.y < baseButton.frame.origin.y + baseButton.frame.size.height) {
        return baseButton;
    }
    
    for (int i = 0; i < count; i++) {
        UIButton *button = (UIButton *)[self viewWithTag:TOOLBUTTONTAG + i];
        if (point.x > button.frame.origin.x
            && point.x < button.frame.origin.x + button.frame.size.width
            && point.y > button.frame.origin.y
            && point.y < button.frame.origin.y + button.frame.size.height) {
            return button;
        }
    }
    
    return nil;
}



- (void) setIsPlaying:(BOOL)temp{
    isPlaying = temp;
    UIButton *button = (UIButton *)[self viewWithTag:TOOLBUTTONTAG + 2];
    if (!isPlaying) {
        [button setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    }else{
        [button setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    }
}

- (BOOL) isPlaying{
    return isPlaying;
}

#pragma mark -
#pragma mark ToolBarButtons
- (void) toolBarButtonClick:(id)sender{
    UIButton *button = (UIButton *)sender;
    [self closeItems];
    if (button.tag == TOOLBUTTONTAG + 2) {
        self.isPlaying = !self.isPlaying;
    }
    if ([delegate respondsToSelector:@selector(didSelectedAtIndex:)]) {
        [delegate didSelectedAtIndex:button.tag - TOOLBUTTONTAG];
    }
}


- (void) layoutSubviews{
    /*
    CGRect rect = CGRectNull;
    switch (position) {
        case CircleToolBarLeftTop:{
            rect = CGRectMake(0, 0, ICONWIDTH, ICONWIDTH);
            break;
        }
        case CircleToolBarLeftBottom:{
            rect = CGRectMake(0, self.frame.size.height - ICONWIDTH, ICONWIDTH, ICONWIDTH);
            break;
        }
        case CircleToolBarRightTop:{
            rect = CGRectMake(self.frame.size.width - ICONWIDTH, 0, ICONWIDTH, ICONWIDTH);
            break;
        }
        case CircleToolBarRightBottom:{
            rect = CGRectMake(self.frame.size.width - ICONWIDTH, self.frame.size.height - ICONWIDTH, ICONWIDTH, ICONWIDTH);
            break;
        }
        default:
            break;
    }
    baseButton.frame = rect;
    for (int i = 0; i < count; i++) {
        UIButton *button = (UIButton *)[self viewWithTag:TOOLBUTTONTAG + i];
        button.center = baseButton.center;
    }
    basePoint = baseButton.center;
    [self refreshCoordinates];
    
    showed = NO;
     */
    
}

@end
